package com.itbooking.core.sync;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class SyncConfiguration {


    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(10);
        // 线程池维护线程的最大数量，只有在缓冲队列满了以后才会去申请
        executor.setMaxPoolSize(100);
        // 缓冲队列
        executor.setQueueCapacity(50);
        // 线程的空闲时间，当某些线程空闲的时间超过了指定的时间就会被销毁
        executor.setKeepAliveSeconds(200);
        // 异步方法内部线程的名称
        executor.setThreadNamePrefix("icoding-thread-");

        /*
         * 当线程池的任务缓冲队列已满，并且线程中的线程数目达到了maxnumpoolSize,如果还有任务到来就会采用任务拒绝策略
         * 通常有四种策略
         * ThreadPoolExecutor.AbortPolicy 丢弃任务并抛出RejectedExecutorException异常
         * ThreadPoolExecutor.DiscardPolicy 也是丢弃任务，但是不抛出异常
         * ThreadPoolExecutor.DiscardOldPolicy 丢弃队列最前面的任务，然后重新长沙执行任务。
         * ThreadPoolExecutor.CallerRunsPolicy 重试添加当前的任务，自动重复调用execute()方法，直到成功。
         * */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
